<template>
  <div class="video-box" ref="videoBox">
    <video
      id="video"
      preload
      autoplay
      loop
      muted
      :width="dom.width"
      :height="dom.height"
    ></video>
    <canvas id="canvas" :width="dom.width" :height="dom.height"></canvas>
    <canvas id="screenshotCanvas"></canvas>
  </div>
</template>

<script>
import "../lib/tracking/build/tracking.js";
import "../lib/tracking/build/data/face-min.js";

export default {
  data() {
    return {
      video: null,
      screenshotCanvas: null,
      uploadLock: true, // 上传锁
      dom: {
        width: 0,
        height: 0,
      },
    };
  },
  async mounted() {
    await this.$nextTick();
    this.dom = {
      width: this.$refs.videoBox.clientWidth,
      height: this.$refs.videoBox.clientHeight,
    };
    console.log(this.dom);
    setTimeout(() => {
      this.init();
    });
  },
  methods: {
    // 初始化设置
    init() {
      this.video = document.getElementById("video");
      this.screenshotCanvas = document.getElementById("screenshotCanvas");

      let canvas = document.getElementById("canvas");
      let context = canvas.getContext("2d");

      // 固定写法
      let tracker = new window.tracking.ObjectTracker("face");
      tracker.setInitialScale(4);
      tracker.setStepSize(2);
      tracker.setEdgesDensity(0.1);
      window.tracking.track("#video", tracker, {
        camera: true,
      });

      tracker.on("track", (event) => {
        // 检测出人脸 绘画人脸位置
        context.clearRect(0, 0, canvas.width, canvas.height);
        event.data.forEach((rect) => {
          context.strokeStyle = "#07C160";
          context.strokeRect(rect.x, rect.y, rect.width, rect.height);
          // 上传图片
          // _this.uploadLock && _this.screenshotAndUpload();
          this.screenshotAndUpload();
        });
      });
    },
    // 上传图片
    screenshotAndUpload() {
      // 绘制当前帧图片转换为base64格式
      let canvas = this.screenshotCanvas;
      let video = this.video;
      let ctx = canvas.getContext("2d");
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      let base64Img = canvas.toDataURL("image/jpeg");

      // 使用 base64Img 请求接口即可
      this.$emit("getTrackingFace", base64Img);
      // 请求接口成功以后打开锁
      // this.uploadLock = true;
    },
  },
};
</script>

<style scoped>
/* 绘图canvas 不需显示隐藏即可 */
#screenshotCanvas {
  display: none;
}

.video-box {
  position: relative;
  width: 100%;
  height: 100%;
}

video,
canvas {
  transform: rotateY(180deg);
  position: absolute;
  top: 0;
  left: 0;
  border: #000000 5px solid;
  object-fit: cover;
}
</style>
